
using System;

namespace Loading.Models {
    public class BrassLot {
        public int BrassLotId { get; set; }
        public string Name { get; set; }
        public BrassLot ParentLot { get; set; }
        public string Source { get; set; }
        public int TimesFired {
            get {
                return ComputeTimesFired();
            }
        }
        public int? OriginTimesFired { get; set; }
        public int Count { get; set; }

        public BrassLot PullRounds(int roundsToPull) {
            if (roundsToPull > Count) {
                throw new Exception("Tried to pull " + roundsToPull + " rounds from " + Count);
            }
            var childLot = new BrassLot {
                ParentLot = this,
                Count = roundsToPull,
                Name = "Child of " + Name,
                Source = "Pulled " + roundsToPull + " rounds from " + Name
            };
            Count -= roundsToPull;
            return childLot;
        }

        private int ComputeTimesFired() {
            if (OriginTimesFired != null) {
                return OriginTimesFired.Value;
            }
            if (ParentLot == null) {
                return 0;
            }
            return 1 + ParentLot.TimesFired;
        }

        public BrassLot Merge(BrassLot lotToMerge)
        {
            BrassLot newLot = new BrassLot
                                  {
                                      Count = Count + lotToMerge.Count,
                                      Source = "Merged lots " + Name + " and " + lotToMerge.Name,
                                      ParentLot = this,
                                      Name = Source
                                  };
            return newLot;

        }
    }
}
